﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using RepertorySystem.Models;

namespace RepertorySystem.Controllers
{
    [Authorize]
    public class BooksController : ApiController
    {
        private BookDbContext db = new BookDbContext();
   
        // GET: api/Books
        public IQueryable<BookModels> GetBooks()
        {
            return db.Books;
        }

        // GET: api/Books/5
        [ResponseType(typeof(BookModels))]
        public IHttpActionResult GetBookModels(int id)
        {
            BookModels bookModels = db.Books.Find(id);
            if (bookModels == null)
            {
                return NotFound();
            }

            return Ok(bookModels);
        }


        // PUT: api/Books/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutBookModels(int id, BookModels bookModels)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != bookModels.ID)
            {
                return BadRequest();
            }

            db.Entry(bookModels).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookModelsExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Books
        [ResponseType(typeof(BookModels))]
        public IHttpActionResult PostBookModels(BookModels bookModels)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Books.Add(bookModels);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = bookModels.ID }, bookModels);
        }

        // DELETE: api/Books/5
        [ResponseType(typeof(BookModels))]
        public IHttpActionResult DeleteBookModels(int id)
        {
            BookModels bookModels = db.Books.Find(id);
            if (bookModels == null)
            {
                return NotFound();
            }

            db.Books.Remove(bookModels);
            db.SaveChanges();

            return Ok(bookModels);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool BookModelsExists(int id)
        {
            return db.Books.Count(e => e.ID == id) > 0;
        }
    }
}